<%@page import="com.torfox.entities.LogRecord"%>
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<style type="text/css">@import "js/jquery.timeentry.package-1.4.9/jquery.timeentry.css";</style> 
<script type="text/javascript" src="js/jquery.timeentry.package-1.4.9/jquery.timeentry.js"></script>
<script type="text/javascript" src="js/jquery.truncate/jquery.truncate.min.js"></script>
<div class="filters">
	<form:form method="post" action="logs.do" modelAttribute="model">

		<div class="filter-field">
			<label for="filter_level">Level</label>
			<form:select id="filter_level" path="filterLevel" >
				<form:option value="" label="Select" />
				<form:options items="${levels}"/>
			</form:select>
		</div>

		<div class="filter-field">
			<label for="filter_sender">Where</label>
			<form:select id="filter_sender" path="sender" >
				<form:option value="" label="Select" />
				<form:options items="${senders}"/>
			</form:select>
		</div>
		
		<div class="filter-field">
			<label for="filter_date">Date</label>
			<form:input id="filter_date" type="text" name="date" path="date" autocomplete="off" />
		</div>
		
		<div class="filter-field">
			<label for="filter_start">Start</label>
			<form:input id="filter_start" type="text" name="timeStart" path="timeStart" />
		</div>
		
		<div class="filter-field">
			<label for="filter_end">End</label>
			<form:input id="filter_end" type="text" name="timeEnd" path="timeEnd" />
		</div>
		
		<div class="filter-field">	
			<label for="filter_level">Class</label>
			<form:input id="filter_level" type="text" name="filterClass" path="filterClass" />
		</div>
		
		<div class="filter-field">
			<label for="filter_pattern">Pattern</label>
			<form:input id="filter_pattern" type="text" name="filterPattern" path="filterPattern"/>
		</div>
		
		<div class="filter-field">
			<label for="filter_exception">Exception</label>
			<form:input id="filter_exception" type="text" name="exceptionPattern" path="filterExceptionClass"/>
		</div>
		
		<div class="filter-field">
			<label for="filter_limit">Limit</label>
			<form:input id="filter_limit" type="text" name="limit" path="limit"/>
		</div>
		
		<label for="golive">Live</label>
		<input id="golive" type="checkbox"/>
		
		<button >Submit</button>
	</form:form>
</div>
<table class="logs">
	<col style="width: 5%"/>
	<col style="width: 8%"/>
	<col style="width: 8%"/>
	<col style="width: 25%"/>
	<col style="width: 40%"/>
	<col style="width: 14%"/>
	<thead>
		<tr>
			<th width="40">LEVEL</th>
			<th width="100">Where</th>
			<th width="100">When</th>
			<th width="300">Class.method(line)</th>
			<th width="400">Message</th>
			<th width="200">Exception</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${records}" var="record">
			<tr>
				<td>${record.level}</td>
				<td>${record.sender}</td>
				<jsp:useBean id="dateValue" class="java.util.Date" />
				<jsp:setProperty name="dateValue" property="time" value="${record.timestamp}" />
				<td><fmt:formatDate value="${dateValue}" pattern="yyyy-MM-dd HH:mm:ss" /></td>
				<td><%= StringUtils.substringAfterLast(((LogRecord)pageContext.getAttribute("record")).getClassName(), ".") %>.${record.methodName}(${record.lineNumber})</td>
				<td><span class="message-text" title="('${fn:escapeXml(record.message)}')">${fn:substring(record.message, 0, 80)}</span></td>
				<td><span onclick="showStackTrace(${record.id});">${record.exceptionClass}</span></td>
			</tr>
		</c:forEach>
	</tbody>
</table>
<div id="dialog" title="Stack Dialog" style="display: none">
</div>
<div id="message_dialog" title="message" style="display: none">
</div>
<script type="text/javascript">
$(function() {
	$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
	$("input#filter_date").datepicker({ dateFormat: 'yy-mm-dd' });
	$("input#filter_start").timeEntry({show24Hours: true, showSeconds: true});
	$("input#filter_end").timeEntry({show24Hours: true, showSeconds: true});
	$("input#filter_exception").autocomplete({
	    source: function( term, callback) {
	    	$.getJSON('exceptions.do', {term: term.term}, function(json) {
	    		callback( json.exceptions);
	    	})
	    }
	});
	$('#golive').change( function() {
		var val = $('#golive').attr('checked');
		if( val) {
			liveLog.start();
		} else {
			liveLog.stop();
		}
	});
	$('.message-text').live('click', function() {
		displayMessage(this.title);
	});
});
function showStackTrace(recordId) {
	$.getJSON("record.do", {id : recordId}, function(json) {
		$('#dialog').html("<pre>" + json.record.stackTrace + "</pre>");
		$('#dialog').dialog({ modal: true, title: json.record.message, height: 500, width: 700});
	});
}
function displayMessage(message) {
	$('#message_dialog').html("<pre>" + message + "</pre>");
	$('#message_dialog').dialog({ modal: true, height: 500, width: 700});
}
if (!window.WebSocket)
  alert("WebSocket not supported by this browser");

function createLocation() {
	var base = 'ws://' + window.location.hostname + ':9091/logging/connect.ws';
	var query = '';
	if( $('#filter_level').val()) {
		query = 'level=' + $('#filter_level').val();
	}
	if( $('#filter_level').val()) {
		if( query != '') {
			query += '&';
		}
		query = 'sender=' + $('#filter_sender').val();
	}
	url = base + (query != '' ? '?' : '') + query;
	return url;
}
var liveLog = {
  start: function() {
    var location = createLocation();
    this._ws=new WebSocket(location,"org.torfox.logs");
    this._ws.onopen=this._onopen;
    this._ws.onmessage=this._onmessage;
    this._ws.onclose=this._onclose;
  },
  
  stop: function() {
	  if( this._ws) {
	    this._ws.close();
	  }
  },
  
  _onopen: function(){
    $('#golive').attr('checked', true);
  },
  
  _send: function(message){
    if (this._ws)
      this._ws.send(message);
  },

  _onmessage: function(m) {
    if (m.data){
    	appendMessage( m.data);
    }
  },
  
  _onclose: function(m) {
   this._ws=null;
   $('#golive').attr('checked', false);
  }
  
};

function appendMessage(json) {
  var m = $.parseJSON(json);
  /* console.log(m.message); */
  var tr = $('<tr>');
  $('table.logs tr:first').after(tr);
  tr.append('<td>' + m.level + '</td>' +
		  '<td>' + m.sender + '</td>' +
		  '<td>' + parseTimestamp( m.timestamp) + '</td>' +
		  '<td>' + m.className + '.' + m.methodName + '(' + m.lineNumber + ')</td>' +
		  '<td>' + m.message + '</td>' +
		  '<td>' + m.exceptionClass + '</td>');
  $(tr).effect("highlight", {}, 10000);
}
function parseTimestamp(ts) {
	var day = new Date();
	day.setTime(ts);
 	return day.getFullYear() + ':' + leadingZero((day.getMonth() + 1)) + ':' + leadingZero(day.getDay()) + ' ' + 
		leadingZero(day.getHours()) + ':' + leadingZero(day.getMinutes()) + ':' + leadingZero(day.getSeconds());
}
function leadingZero(num) {
	if( num < 10) return '0' + num;
	return num;
}

</script>